package info.harmonyshive.imagepicker.slice;

import com.yalantis.ucrop.util.LogUtils;
import info.harmonyshive.imagepicker.BasicAbility;
import info.harmonyshive.imagepicker.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;
import ohos.data.resultset.ResultSet;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;


public class ImagePickerAbilitySlice extends AbilitySlice {
    TableLayout tableLayout = new TableLayout(this);
    TableLayout.LayoutConfig layoutConfig = new TableLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
    ScrollView scrollView = new ScrollView(this);
    DirectionalLayout directionalLayout = new DirectionalLayout(this);
    private static CommonDialog builder;
    Uri mUri;
    public interface PickerOptionListener {
        void onTakeCameraSelected();

        void onChooseGallerySelected();
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        tableLayout.setColumnCount(4);
        tableLayout.setLayoutConfig(layoutConfig);
        tableLayout.setOrientation(Component.HORIZONTAL);
        pickFromGallery();

        directionalLayout.addComponent(tableLayout);

        scrollView.setLayoutConfig(layoutConfig);
        scrollView.addComponent(directionalLayout);
        setUIContent(scrollView);
    }

    private void pickFromGallery() {
        DataAbilityHelper helper = DataAbilityHelper.creator(this);
        try {
            // columns为null则查询记录所有字段，当前例子表示查询id字段
            ResultSet resultSet = helper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,
                    new String[]{AVStorage.Images.Media.ID},
                    null);
            while (resultSet != null && resultSet.goToNextRow()) {
                PixelMap pixelMap = null;
                ImageSource imageSource = null;
                Image image = new Image(this);
                image.setWidth(250);
                image.setHeight(250);
                image.setMarginsLeftAndRight(10, 10);
                image.setMarginsTopAndBottom(10, 10);
                image.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                // 获取id字段的值
                int id = resultSet.getInt(resultSet.getColumnIndexForName(AVStorage.Images.Media.ID));
                LogUtils.LogInfo("wwwwwwwwww:",String.valueOf(resultSet));
                Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
                LogUtils.LogInfo("wwwwwwwwww:",String.valueOf(uri));
                FileDescriptor fd = helper.openFile(uri, "r");
                ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                try {
                    imageSource = ImageSource.create(fd, null);
                    pixelMap = imageSource.createPixelmap(null);
                    int height = pixelMap.getImageInfo().size.height;
                    int width = pixelMap.getImageInfo().size.width;
                    float sampleFactor = Math.max(height /250f, width/250f);
                    decodingOptions.desiredSize = new Size((int) (width/sampleFactor), (int)(height/sampleFactor));
                    pixelMap = imageSource.createPixelmap(decodingOptions);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (imageSource != null) {
                        imageSource.release();
                    }
                }
                image.setPixelMap(pixelMap);
                image.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        gotoCrop(uri);
                    }
                });
                tableLayout.addComponent(image);
            }
        } catch (DataAbilityRemoteException | FileNotFoundException e) {
            e.printStackTrace();
        }
    }



    private PixelMap loadImage() {
        DataAbilityHelper helper = DataAbilityHelper.creator(this);
        try {
            // columns为null，查询记录所有字段，当前例子表示查询id字段
            ResultSet resultSet = helper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, new String[]{AVStorage.Images.Media.ID}, null);
            resultSet.goToLastRow();
            PixelMap pixelMap = null;
            ImageSource imageSource = null;
            // 获取id字段的值
            int id = resultSet.getInt(resultSet.getColumnIndexForName(AVStorage.Images.Media.ID));
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
            FileDescriptor fd = helper.openFile(uri, "r");
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            try {
                imageSource = ImageSource.create(fd, null);
                pixelMap = imageSource.createPixelmap(decodingOptions);
                return pixelMap;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (imageSource != null) {
                    imageSource.release();
                }
            }

        } catch (DataAbilityRemoteException | FileNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }
    public static void showImagePickerOptions(Context context, PickerOptionListener listener) {
        builder = new CommonDialog(context);
        DirectionalLayout layout = (DirectionalLayout) LayoutScatter.getInstance(context).parse(ResourceTable.Layout_layout_options, null, false);
        builder.setContentCustomComponent(layout)
                .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                .setAlignment(LayoutAlignment.CENTER)
                .setAutoClosable(true)
                .show();
        Button txtGallery = (Button) layout.findComponentById(ResourceTable.Id_opt_gallary);
        txtGallery.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                listener.onChooseGallerySelected();
                builder.destroy();
            }
        });

    }
    private final int CODE_CPT = 100;
    private void gotoCrop(Uri uri){
        Intent intent = new Intent();
        intent.setUri(uri);
        present(new BasicAbility(),intent);
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
